package com.bml.architect.proivder.service;

import com.bml.architect.DemoListener;
import com.bml.architect.DemoService;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service(version = "callback",methods = {@Method(name = "sayHello",arguments = {@Argument(index = 2,callback = true)})},callbacks = 3)
public class CallBackDemoServiceImpl implements DemoService {

    private final Map<String, DemoListener> listenerMap = new ConcurrentHashMap<>();

    public CallBackDemoServiceImpl() {
        new Thread(() -> {

            for (; ; ) {
                if (listenerMap.isEmpty())
                    Thread.yield();
                listenerMap.forEach((k, v) -> {
                    v.callback(getChanged(k));
                });
                listenerMap.clear();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }, "callBackInvoke-thread").start();
    }

    @Override
    public String sayHello(String name) {
        return null;
    }

    private String getChanged(String key) {
        return "Changed: " + key+ ":" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    @Override
    public String sayHello(String name, String key, DemoListener listener) {
        System.out.println("执行了默认的服务 " + name);

        listenerMap.put(key, listener);
        URL url = RpcContext.getContext().getUrl();
        return String.format("%s:%s,hello,%s", url.getProtocol(), url.getPort(), name);
    }
}
